package com.qiuguo.rtsp.utils;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Optional;

/**
 * @author zhangll
 * @email: 524631266@qq.com
 * @create_date: 2025/6/12
 */
public class IPConverter extends ClassicConverter {
    private static final Logger log = LoggerFactory.getLogger(IPConverter.class);
    private final Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1L).build();

    public IPConverter() {
    }

    public String getIpv4() {
        try {
            return (String)this.cache.get("ip", () -> {
                // 首先尝试从环境变量获取宿主机IP
                String hostIp = System.getenv("HOST_IP");
                if (hostIp != null && !hostIp.isEmpty()) {
                    log.info("从环境变量HOST_IP获取到宿主机IP: {}", hostIp);
                    return hostIp;
                }
                
                // 尝试获取宿主机IP（适用于Docker环境）
                hostIp = System.getenv("DOCKER_HOST_IP");
                if (hostIp != null && !hostIp.isEmpty()) {
                    log.info("从环境变量DOCKER_HOST_IP获取到宿主机IP: {}", hostIp);
                    return hostIp;
                }
                
                // 获取本机IP地址
                return getLocalHostAddress();
            });
        } catch (Exception var2) {
            log.error("ip convert error", var2);
            return "127.0.0.1";
        }
    }

    /**
     * 获取本机IP地址，优先返回192.168开头的局域网IP
     */
    private String getLocalHostAddress() throws Exception {
        String preferredIP = null;
        String fallbackIP = null;
        
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            // 跳过回环接口、虚拟接口和docker网桥
            if (networkInterface.isLoopback() || networkInterface.isVirtual() || 
                networkInterface.getName().startsWith("docker") || 
                networkInterface.getName().startsWith("br-")) {
                continue;
            }
            
            Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = addresses.nextElement();
                // 检查是否为IPv4地址且不是回环地址
                if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1) {
                    String ip = address.getHostAddress();
                    // 排除docker相关的IP段
                    if (!ip.startsWith("172.17.") && !ip.startsWith("172.18.") && 
                        !ip.startsWith("172.19.") && !ip.startsWith("172.20.")) {
                        
                        // 优先选择192.168开头的IP
                        if (ip.startsWith("192.168")) {
                            log.info("找到优先IP地址: {}", ip);
                            return ip;
                        }
                        
                        // 保存备选IP
                        if (preferredIP == null && 
                            (ip.startsWith("10.") || ip.startsWith("172."))) {
                            preferredIP = ip;
                        } else if (fallbackIP == null) {
                            fallbackIP = ip;
                        }
                    }
                }
            }
        }
        
        // 返回找到的最优IP
        if (preferredIP != null) {
            log.info("使用备选IP地址: {}", preferredIP);
            return preferredIP;
        }
        
        if (fallbackIP != null) {
            log.info("使用fallback IP地址: {}", fallbackIP);
            return fallbackIP;
        }
        
        // 如果没有找到合适的IP，返回默认值
        String defaultIp = InetAddress.getLocalHost().getHostAddress();
        log.info("使用默认方式获取IP地址: {}", defaultIp);
        return defaultIp;
    }

    public static boolean isIpV4(String ipStr) {
        if (ipStr != null && !ipStr.isEmpty()) {
            String regex = "^(((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))$";
            return ipStr.matches(regex);
        } else {
            return false;
        }
    }

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        return this.getIpv4();
    }
}
